<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width,initial-scale=1"><title>（Vue源码二）Vue实例挂载流程 | Jeffery Blog</title><meta name="keywords" content="vue, vue 源码"><meta name="author" content="志非"><meta name="copyright" content="志非"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="vue, vue 源码，Vue 源码目录及构建过程分析">
<meta property="og:type" content="article">
<meta property="og:title" content="（Vue源码二）Vue实例挂载流程">
<meta property="og:url" content="https://fif.gitee.io/blog/2021/04/17/vue/vue-code-4.debugger/index.html">
<meta property="og:site_name" content="Jeffery Blog">
<meta property="og:description" content="vue, vue 源码，Vue 源码目录及构建过程分析">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://gitee.com/FIF/pic-beg/raw/master/images/vue/1_b2Ig4HR2UOQEV5I2QnQrrw.png">
<meta property="article:published_time" content="2021-04-16T16:00:00.000Z">
<meta property="article:modified_time" content="2021-04-22T16:00:00.000Z">
<meta property="article:author" content="志非">
<meta property="article:tag" content="vue">
<meta property="article:tag" content="vue 源码">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://gitee.com/FIF/pic-beg/raw/master/images/vue/1_b2Ig4HR2UOQEV5I2QnQrrw.png"><link rel="shortcut icon" href="/blog/img/home/avatar.jpeg"><link rel="canonical" href="https://fif.gitee.io/blog/2021/04/17/vue/vue-code-4.debugger/"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//fonts.googleapis.com" crossorigin=""/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/blog/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/node-snackbar/dist/snackbar.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/instantsearch.js@2.10.5/dist/instantsearch.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/instantsearch.js@2.10.5/dist/instantsearch.min.js" defer></script><script async="async" src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script><script>(adsbygoogle = window.adsbygoogle || []).push({
  google_ad_client: '',
  enable_page_level_ads: 'true'
});</script><link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Titillium+Web&amp;display=swap" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = { 
  root: '/blog/',
  algolia: {"appId":"QYKLQ4BSGP","apiKey":"d45fc66694b4260b20711a30fdb5c4e1","indexName":"jeffery-blog","hits":{"per_page":6},"languages":{"input_placeholder":"搜索文章","hits_empty":"找不到您查询的内容：${query}","hits_stats":"找到 ${hits} 条结果，用时 ${time} 毫秒"}},
  localSearch: undefined,
  translate: {"defaultEncoding":2,"translateDelay":0,"msgToTraditionalChinese":"繁","msgToSimplifiedChinese":"簡"},
  noticeOutdate: {"limitDay":200,"position":"top","messagePrev":"本文修改于","messageNext":"天前，如果本文有一定的时效性，那么本文可能已经失效~"},
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: true,
    post: false
  },
  runtime: '天',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'mediumZoom',
  Snackbar: {"chs_to_cht":"你已切换为繁体","cht_to_chs":"你已切换为简体","day_to_night":"你已切换为深色模式","night_to_day":"你已切换为浅色模式","bgLight":"#49b1f5","bgDark":"#121212","position":"bottom-left"},
  source: {
    jQuery: 'https://cdn.jsdelivr.net/npm/jquery@latest/dist/jquery.min.js',
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/js/jquery.justifiedGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/css/justifiedGallery.min.css'
    },
    fancybox: {
      js: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.js',
      css: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: true,
  isanchor: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = { 
  isPost: true,
  isHome: false,
  isHighlightShrink: true,
  isToc: true,
  postUpdate: '2021-04-23 00:00:00'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    })(window)</script><meta name="generator" content="Hexo 5.4.0"><link rel="alternate" href="/blog/atom.xml" title="Jeffery Blog" type="application/atom+xml">
</head><body><div id="loading-box"><div class="loading-left-bg"></div><div class="loading-right-bg"></div><img class="load-image" src= "" data-lazy-src="/blog/img/loading.gif" alt=""/></div><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="author-avatar"><img class="avatar-img" src= "" data-lazy-src="/blog/img/home/avatar.jpeg" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="site-data"><div class="data-item is-center"><div class="data-item-link"><a href="/blog/archives/"><div class="headline">文章</div><div class="length-num">12</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/blog/tags/"><div class="headline">标签</div><div class="length-num">6</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/blog/categories/"><div class="headline">分类</div><div class="length-num">7</div></a></div></div></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/blog/"><i class="fa-fw fa fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/blog/archives/"><i class="fa-fw fa fa-archive"></i><span> 时间轴</span></a></div><div class="menus_item"><a class="site-page" href="/blog/tags/"><i class="fa-fw fa fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/blog/categories/"><i class="fa-fw fa fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> 媒体</span><i class="fas fa-chevron-down expand"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/blog/books/"><i class="fa-fw fas fa-book"></i><span> 阅读</span></a></li><li><a class="site-page child" href="/blog/music/"><i class="fa-fw fa fa-music"></i><span> 音乐</span></a></li><li><a class="site-page child" href="/blog/movies/"><i class="fa-fw fa fa-film"></i><span> 电影</span></a></li><li><a class="site-page child" href="/blog/gallery/"><i class="fa-fw far fa-image"></i><span> 相册</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/blog/box/"><i class="fa-fw fab fa-xbox"></i><span> 聚宝盒</span></a></div><div class="menus_item"><a class="site-page" href="/blog/talk/"><i class="fa-fw far fa-comment"></i><span> 微语</span></a></div><div class="menus_item"><a class="site-page" href="/blog/link/"><i class="fa-fw fa fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/blog/about/"><i class="fa-fw fa fa-heart"></i><span> 关于</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('https://gitee.com/FIF/pic-beg/raw/master/images/vue/1_b2Ig4HR2UOQEV5I2QnQrrw.png')"><nav id="nav"><span id="blog_name"><a id="site-name" href="/blog/">Jeffery Blog</a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/blog/"><i class="fa-fw fa fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/blog/archives/"><i class="fa-fw fa fa-archive"></i><span> 时间轴</span></a></div><div class="menus_item"><a class="site-page" href="/blog/tags/"><i class="fa-fw fa fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/blog/categories/"><i class="fa-fw fa fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> 媒体</span><i class="fas fa-chevron-down expand"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/blog/books/"><i class="fa-fw fas fa-book"></i><span> 阅读</span></a></li><li><a class="site-page child" href="/blog/music/"><i class="fa-fw fa fa-music"></i><span> 音乐</span></a></li><li><a class="site-page child" href="/blog/movies/"><i class="fa-fw fa fa-film"></i><span> 电影</span></a></li><li><a class="site-page child" href="/blog/gallery/"><i class="fa-fw far fa-image"></i><span> 相册</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/blog/box/"><i class="fa-fw fab fa-xbox"></i><span> 聚宝盒</span></a></div><div class="menus_item"><a class="site-page" href="/blog/talk/"><i class="fa-fw far fa-comment"></i><span> 微语</span></a></div><div class="menus_item"><a class="site-page" href="/blog/link/"><i class="fa-fw fa fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/blog/about/"><i class="fa-fw fa fa-heart"></i><span> 关于</span></a></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">（Vue源码二）Vue实例挂载流程</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2021-04-16T16:00:00.000Z" title="发表于 2021-04-17 00:00:00">2021-04-17</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2021-04-22T16:00:00.000Z" title="更新于 2021-04-23 00:00:00">2021-04-23</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/blog/categories/%E5%89%8D%E7%AB%AF/">前端</a><i class="fas fa-angle-right post-meta-separator"></i><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/blog/categories/%E5%89%8D%E7%AB%AF/vue/">vue</a><i class="fas fa-angle-right post-meta-separator"></i><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/blog/categories/%E5%89%8D%E7%AB%AF/vue/vue-%E6%BA%90%E7%A0%81/">vue 源码</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">4.9k</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>19分钟</span></span><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="（Vue源码二）Vue实例挂载流程"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h2 id="Vue函数挂载API"><a href="#Vue函数挂载API" class="headerlink" title="Vue函数挂载API"></a>Vue函数挂载API</h2><p><code>Vue</code> 之所以能实现各种高级的功能，比如响应式、编译、组件渲染，和它身上拥有丰富的 <code>API</code> 有关，<code>Vue</code> 在实例化前会挂载 <code>API</code> ，它的 <code>API</code> 分为全局 <code>API</code> 和原型方法，下面从入口文件到<code>Vue</code>构造函数挂载 <code>API</code> 的流程图：</p>
<p><a data-fancybox target="_blank" rel="noopener" href="https://gitee.com/FIF/pic-beg/raw/master/images/vue/process.8f86c136.png"><img src= "" data-lazy-src="https://gitee.com/FIF/pic-beg/raw/master/images/vue/process.8f86c136.png"></a></p>
<h2 id="initGlobalAPI挂载全局方法"><a href="#initGlobalAPI挂载全局方法" class="headerlink" title="initGlobalAPI挂载全局方法"></a>initGlobalAPI挂载全局方法</h2><p><code>initGlobalAPI</code> 挂载全局方法，它的入口文件在 <code>src/core/index.js</code></p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> Vue <span class="keyword">from</span> <span class="string">&#x27;./instance/index&#x27;</span></span><br><span class="line"><span class="keyword">import</span> &#123; initGlobalAPI &#125; <span class="keyword">from</span> <span class="string">&#x27;./global-api/index&#x27;</span></span><br><span class="line">initGlobalAPI(Vue)</span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> Vue</span><br></pre></td></tr></table></figure>

<p><code>initGlobalAPI()</code>函数定义在 <code>src/core/global-api/index.js</code> 中：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="function"><span class="keyword">function</span> <span class="title">initGlobalAPI</span> (<span class="params">Vue: GlobalAPI</span>) </span>&#123;</span><br><span class="line">  <span class="comment">// config</span></span><br><span class="line">  <span class="keyword">const</span> configDef = &#123;&#125;</span><br><span class="line">  <span class="comment">// config 默认配置</span></span><br><span class="line">  configDef.get = <span class="function">() =&gt;</span> config</span><br><span class="line"></span><br><span class="line">  <span class="comment">// 使用代理，挂载 config 属性，get 方法定义了默认的配置</span></span><br><span class="line">  <span class="built_in">Object</span>.defineProperty(Vue, <span class="string">&#x27;config&#x27;</span>, configDef)</span><br><span class="line"></span><br><span class="line">  <span class="comment">// 工具方法</span></span><br><span class="line">  Vue.util = &#123;</span><br><span class="line">    warn,</span><br><span class="line">    extend,</span><br><span class="line">    mergeOptions,</span><br><span class="line">    defineReactive</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  Vue.set = set</span><br><span class="line">  Vue.delete = del</span><br><span class="line">  Vue.nextTick = nextTick</span><br><span class="line"></span><br><span class="line">  <span class="comment">// 2.6 explicit observable API</span></span><br><span class="line">  Vue.observable = &lt;T&gt;(obj: T): <span class="function"><span class="params">T</span> =&gt;</span> &#123;</span><br><span class="line">    observe(obj)</span><br><span class="line">    <span class="keyword">return</span> obj</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  Vue.options = <span class="built_in">Object</span>.create(<span class="literal">null</span>)</span><br><span class="line">  ASSET_TYPES.forEach(<span class="function"><span class="params">type</span> =&gt;</span> &#123;</span><br><span class="line">    Vue.options[type + <span class="string">&#x27;s&#x27;</span>] = <span class="built_in">Object</span>.create(<span class="literal">null</span>)</span><br><span class="line">  &#125;)</span><br><span class="line"></span><br><span class="line">  Vue.options._base = Vue</span><br><span class="line"></span><br><span class="line">  <span class="comment">//  注册 keep-alive 全局组件</span></span><br><span class="line">  extend(Vue.options.components, builtInComponents)</span><br><span class="line"></span><br><span class="line">  initUse(Vue) <span class="comment">// 挂载 use 静态方法</span></span><br><span class="line">  initMixin(Vue) <span class="comment">// 挂载 mixin 静态方法，mergeOptions 方法合并 options</span></span><br><span class="line">  initExtend(Vue) <span class="comment">// 挂载 extend 静态方法</span></span><br><span class="line">  initAssetRegisters(Vue) <span class="comment">// 挂载 component, directive, filter 静态方法</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<p><code>initGlobalAPI</code> 将<code>set</code>、<code>delete</code>、<code>nextTick</code>和<code>observable</code> 等函数直接挂载在<code>Vue</code>上，而其他几种<code>API</code>则是调用了一个以<code>init</code>开头的方法，我们以<code>initAssetRegisters()</code>方法为例</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// [&#x27;component&#x27;,&#x27;directive&#x27;, &#x27;filter&#x27;]</span></span><br><span class="line"><span class="keyword">import</span> &#123; ASSET_TYPES &#125; <span class="keyword">from</span> <span class="string">&#x27;shared/constants&#x27;</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="function"><span class="keyword">function</span> <span class="title">initAssetRegisters</span> (<span class="params">Vue: GlobalAPI</span>) </span>&#123;</span><br><span class="line">  ASSET_TYPES.forEach(<span class="function"><span class="params">type</span> =&gt;</span> &#123;</span><br><span class="line">    Vue[type] = <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">      <span class="comment">// 省略了函数的参数和函数实现代码</span></span><br><span class="line">    &#125;</span><br><span class="line">  &#125;)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>其中<code>ASSET_TYPES</code>是一个定义在<code>src/shared/constants.js</code>中的一个数组，然后在<code>initAssetRegisters()</code>方法中遍历这个数组，依次在<code>Vue</code>构造函数上挂载<code>Vue.component()</code>、<code>Vue.directive()</code>和<code>Vue.filter()</code>方法，另外三种<code>init</code>开头的方法挂载对应的全局<code>API</code>是一样的道理：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// initUse</span></span><br><span class="line"><span class="keyword">export</span> <span class="function"><span class="keyword">function</span> <span class="title">initUse</span>(<span class="params">Vue</span>) </span>&#123;</span><br><span class="line">  Vue.use = <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;&#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// initMixin</span></span><br><span class="line"><span class="keyword">export</span> <span class="function"><span class="keyword">function</span> <span class="title">initMixin</span>(<span class="params">Vue</span>) </span>&#123;</span><br><span class="line">  Vue.mixin = <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;&#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// initExtend</span></span><br><span class="line"><span class="keyword">export</span> <span class="function"><span class="keyword">function</span> <span class="title">initExtend</span>(<span class="params">Vue</span>) </span>&#123;</span><br><span class="line">  Vue.extend = <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>最后，我们发现还差一个<code>Vue.compile()</code>方法，它其实是在<code>runtime+compile</code>版本才会有的一个全局方法，因此它在<code>src/platforms/web/entry-runtime-with-compile.js</code>中被定义：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> Vue <span class="keyword">from</span> <span class="string">&#x27;./runtime/index&#x27;</span></span><br><span class="line"><span class="keyword">import</span> &#123; compileToFunctions &#125; <span class="keyword">from</span> <span class="string">&#x27;./compiler/index&#x27;</span></span><br><span class="line">Vue.compile = compileToFunctions</span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> Vue</span><br></pre></td></tr></table></figure>

<p>根据<code>initGlobalAPI()</code>方法的逻辑，可以得到如下流程图：</p>
<p><img src= "" data-lazy-src="https://gitee.com/FIF/pic-beg/raw/master/images/vue/initGlobalAPIProcess.6d78bbb9.png" alt="initGlobalAPI流程图"></p>
<h2 id="挂载原型方法"><a href="#挂载原型方法" class="headerlink" title="挂载原型方法"></a>挂载原型方法</h2><p>挂载原型方法定义在 <code>src/core/instance/index.js</code>， 也是通过 <code>init</code> 开头</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> &#123; initMixin &#125; <span class="keyword">from</span> <span class="string">&#x27;./init&#x27;</span></span><br><span class="line"><span class="keyword">import</span> &#123; stateMixin &#125; <span class="keyword">from</span> <span class="string">&#x27;./state&#x27;</span></span><br><span class="line"><span class="keyword">import</span> &#123; renderMixin &#125; <span class="keyword">from</span> <span class="string">&#x27;./render&#x27;</span></span><br><span class="line"><span class="keyword">import</span> &#123; eventsMixin &#125; <span class="keyword">from</span> <span class="string">&#x27;./events&#x27;</span></span><br><span class="line"><span class="keyword">import</span> &#123; lifecycleMixin &#125; <span class="keyword">from</span> <span class="string">&#x27;./lifecycle&#x27;</span></span><br><span class="line"><span class="keyword">import</span> &#123; warn &#125; <span class="keyword">from</span> <span class="string">&#x27;../util/index&#x27;</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">Vue</span> (<span class="params">options</span>) </span>&#123;</span><br><span class="line">  <span class="built_in">this</span>._init(options)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 往 Vue 原型上添加属性和方法</span></span><br><span class="line">initMixin(Vue) <span class="comment">// 原型上添加 _init 方法</span></span><br><span class="line">stateMixin(Vue) <span class="comment">// 原型上添加 VUE 实例属性 $data, $props, $set, $delete, $watch</span></span><br><span class="line">eventsMixin(Vue) <span class="comment">// 原型上添加 $on, $once, $off, $emit 方法</span></span><br><span class="line">lifecycleMixin(Vue) <span class="comment">// 原型上添加 _update, $forceUpdate, $destroy 方法</span></span><br><span class="line">renderMixin(Vue) <span class="comment">// 安装运行时辅助工具，原型上添加 $nextTick, _render 方法</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> Vue</span><br></pre></td></tr></table></figure>

<p><code>init</code> 开头的方法定义在<code>instance</code>目录</p>
<figure class="highlight sh"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">|-- instance</span><br><span class="line">|   |-- render-helpers      <span class="comment"># render渲染相关的工具函数目录</span></span><br><span class="line">|   |-- events.js           <span class="comment"># 事件处理相关</span></span><br><span class="line">|   |-- init.js             <span class="comment"># _init等方法相关</span></span><br><span class="line">|   |-- inject.js           <span class="comment"># inject和provide相关</span></span><br><span class="line">|   |-- lifecycle.js        <span class="comment"># 生命周期相关</span></span><br><span class="line">|   |-- proxy.js            <span class="comment"># 代理相关</span></span><br><span class="line">|   |-- render.js           <span class="comment"># 渲染相关</span></span><br><span class="line">|   |-- state.js            <span class="comment"># 数据状态相关</span></span><br><span class="line">|   |-- index.js            <span class="comment"># 入口文件</span></span><br></pre></td></tr></table></figure>

<p>可以看到，目录结构文件有很多，而且包含的面也非常杂，但我们现在只需要对我们最关心的几个部分做介绍：</p>
<ul>
<li><code>events.js</code>：处理事件相关，例如：<code>$on</code>，<code>$off</code>，<code>$emit</code>以及<code>$once</code>等方法的实现。</li>
<li><code>init.js</code>：此部分代码逻辑包含了<code>Vue</code>从创建实例到实例挂载阶段的所有主要逻辑。</li>
<li><code>lifecycle.js</code>：生命周期相关，例如：<code>$destroy</code>、<code>$activated</code>和<code>$deactivated</code>。</li>
<li><code>state.js</code>：数据状态相关，例如：<code>data</code>、<code>props</code>以及<code>computed</code>等。</li>
<li><code>render.js</code>：渲染相关，其中最值得关注的是<code>Vue.prototype._render</code>渲染函数的定义。</li>
</ul>
<h3 id="initMixin-流程"><a href="#initMixin-流程" class="headerlink" title="initMixin 流程"></a>initMixin 流程</h3><p><code>initMixin()</code>方法的主要作用就是在<code>Vue.prototype</code>上定义一个<code>_init()</code>实例方法，接下来我们来看一下<code>_init()</code>函数的具体实现逻辑：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br></pre></td><td class="code"><pre><span class="line">Vue.prototype._init = <span class="function"><span class="keyword">function</span> (<span class="params">options</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">const</span> vm = <span class="built_in">this</span></span><br><span class="line">    <span class="comment">// 1. 合并配置</span></span><br><span class="line">    <span class="keyword">if</span> (options &amp;&amp; options._isComponent) &#123;</span><br><span class="line">      initInternalComponent(vm, options)</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">      vm.$options = mergeOptions(</span><br><span class="line">        resolveConstructorOptions(vm.constructor),</span><br><span class="line">        options || &#123;&#125;,</span><br><span class="line">        vm</span><br><span class="line">      )</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 2.render代理</span></span><br><span class="line">    <span class="keyword">if</span> (process.env.NODE_ENV !== <span class="string">&#x27;production&#x27;</span>) &#123;</span><br><span class="line">      initProxy(vm)</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">      vm._renderProxy = vm</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 3.初始化生命周期、初始化事件中心、初始化inject，</span></span><br><span class="line">    <span class="comment">//   初始化state、初始化provide、调用生命周期</span></span><br><span class="line">    vm._self = vm</span><br><span class="line">    initLifecycle(vm)</span><br><span class="line">    initEvents(vm)</span><br><span class="line">    initRender(vm)</span><br><span class="line">    callHook(vm, <span class="string">&#x27;beforeCreate&#x27;</span>)</span><br><span class="line">    initInjections(vm)</span><br><span class="line">    initState(vm)</span><br><span class="line">    initProvide(vm)</span><br><span class="line">    callHook(vm, <span class="string">&#x27;created&#x27;</span>)</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 4.挂载</span></span><br><span class="line">    <span class="keyword">if</span> (vm.$options.el) &#123;</span><br><span class="line">      vm.$mount(vm.$options.el)</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br></pre></td></tr></table></figure>

<p><code>initMixin</code>整体流程图</p>
<p><img src= "" data-lazy-src="https://gitee.com/FIF/pic-beg/raw/master/images/vue/initMixin.9a4f8f37.png" alt="img"></p>
<h3 id="stateMixin-流程"><a href="#stateMixin-流程" class="headerlink" title="stateMixin 流程"></a>stateMixin 流程</h3><p><code>stateMixin</code>主要是处理跟实例相关的属性和方法，它会在<code>Vue.prototype</code>上定义实例化使用到的属性或者方法，代码在<code>src/core/instance/state.js</code></p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> &#123; set, del &#125; <span class="keyword">from</span> <span class="string">&#x27;../observer/index&#x27;</span></span><br><span class="line"><span class="keyword">export</span> <span class="function"><span class="keyword">function</span> <span class="title">stateMixin</span> (<span class="params">Vue</span>) </span>&#123;</span><br><span class="line">  <span class="comment">// 定义$data, $props</span></span><br><span class="line">  <span class="keyword">const</span> dataDef = &#123;&#125;</span><br><span class="line">  dataDef.get = <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123; <span class="keyword">return</span> <span class="built_in">this</span>._data &#125;</span><br><span class="line">  <span class="keyword">const</span> propsDef = &#123;&#125;</span><br><span class="line">  propsDef.get = <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123; <span class="keyword">return</span> <span class="built_in">this</span>._props &#125;</span><br><span class="line">  <span class="built_in">Object</span>.defineProperty(Vue.prototype, <span class="string">&#x27;$data&#x27;</span>, dataDef)</span><br><span class="line">  <span class="built_in">Object</span>.defineProperty(Vue.prototype, <span class="string">&#x27;$props&#x27;</span>, propsDef)</span><br><span class="line"></span><br><span class="line">  <span class="comment">// 定义$set, $delete, $watch</span></span><br><span class="line">  Vue.prototype.$set = set</span><br><span class="line">  Vue.prototype.$delete = del</span><br><span class="line">  Vue.prototype.$watch = <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>我们可以从上面代码中发现，<code>stateMixin()</code>方法中在<code>Vue.prototype</code>上定义的几个属性或者方法，全部都是和响应式相关的，我们来简要分析一下以上代码：</p>
<ul>
<li><code>$data和$props</code>：根据以上代码，我们发现<code>$data</code>和<code>$props</code>分别是<code>_data</code>和<code>_props</code>的访问代理，从命名中我们可以推测，以下划线开头的变量，我们一般认为是私有变量，然后通过<code>$data</code>和<code>$props</code>来提供一个对外的访问接口，虽然可以通过属性的<code>get()</code>方法去取，但对于这两个私有变量来说是并不能随意<code>set</code>，对于<code>data</code>来说不能替换根实例，而对于<code>props</code>来说它是只读的。因此在原版源码中，还劫持了<code>set()</code>方法，当设置<code>$data</code>或者<code>$props</code>时会报错：</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">if</span> (process.env.NODE_ENV !== <span class="string">&#x27;production&#x27;</span>) &#123;</span><br><span class="line">  dataDef.set = <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">    warn(</span><br><span class="line">      <span class="string">&#x27;Avoid replacing instance root $data. &#x27;</span> +</span><br><span class="line">      <span class="string">&#x27;Use nested data properties instead.&#x27;</span>,</span><br><span class="line">      <span class="built_in">this</span></span><br><span class="line">    )</span><br><span class="line">  &#125;</span><br><span class="line">  propsDef.set = <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">    warn(<span class="string">`$props is readonly.`</span>, <span class="built_in">this</span>)</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ul>
<li><code>$set</code>和<code>$delete</code>：<code>set</code>和<code>delete</code>这两个方法被定义在跟<code>instance</code>目录平级的<code>observer</code>目录下，在<code>stateMixin()</code>中，它们分别赋值给了<code>$set</code>和<code>$delete</code>方法，而在<code>initGlobalAPI</code>中，也同样使用到了这两个方法，只不过一个是全局方法，一个是实例方法。</li>
<li><code>$watch</code>：在<code>stateMixin()</code>方法中，详细实现了<code>$watch()</code>方法，此方法实现的核心是通过一个<code>watcher</code>实例来监听。当取消监听时，同样是使用<code>watcher</code>实例相关的方法，关于<code>watcher</code>我们会在后续响应式章节详细介绍。</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line">Vue.prototype.$watch = <span class="function"><span class="keyword">function</span> (<span class="params"></span></span></span><br><span class="line"><span class="function"><span class="params">    expOrFn: string | <span class="built_in">Function</span>,</span></span></span><br><span class="line"><span class="function"><span class="params">    cb: any,</span></span></span><br><span class="line"><span class="function"><span class="params">    options?: <span class="built_in">Object</span></span></span></span><br><span class="line"><span class="function"><span class="params">  </span>): <span class="title">Function</span> </span>&#123;</span><br><span class="line">    <span class="keyword">const</span> vm: Component = <span class="built_in">this</span></span><br><span class="line">    <span class="keyword">if</span> (isPlainObject(cb)) &#123;</span><br><span class="line">      <span class="keyword">return</span> createWatcher(vm, expOrFn, cb, options)</span><br><span class="line">    &#125;</span><br><span class="line">    options = options || &#123;&#125;</span><br><span class="line">    options.user = <span class="literal">true</span></span><br><span class="line">    <span class="keyword">const</span> watcher = <span class="keyword">new</span> Watcher(vm, expOrFn, cb, options)</span><br><span class="line">    <span class="keyword">if</span> (options.immediate) &#123;</span><br><span class="line">      <span class="keyword">try</span> &#123;</span><br><span class="line">        cb.call(vm, watcher.value)</span><br><span class="line">      &#125; <span class="keyword">catch</span> (error) &#123;</span><br><span class="line">        handleError(error, vm, <span class="string">`callback for immediate watcher &quot;<span class="subst">$&#123;watcher.expression&#125;</span>&quot;`</span>)</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> <span class="function"><span class="keyword">function</span>  (<span class="params"></span>) </span>&#123;</span><br><span class="line">      watcher.teardownunwatchFn()</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br></pre></td></tr></table></figure>



<h3 id="eventsMixin-流程"><a href="#eventsMixin-流程" class="headerlink" title="eventsMixin 流程"></a>eventsMixin 流程</h3><p>在使用<code>Vue</code>做开发的时候，我们一定经常使用到<code>$emit</code>、<code>$on</code>、<code>$off</code>和<code>$once</code>等几个实例方法，<code>eventsMixin</code>主要做的就是在<code>Vue.prototype</code>上定义这四个实例方法：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">export</span> <span class="function"><span class="keyword">function</span> <span class="title">eventsMixin</span> (<span class="params">Vue</span>) </span>&#123;</span><br><span class="line">  <span class="comment">// 定义$on</span></span><br><span class="line">  Vue.prototype.$on = <span class="function"><span class="keyword">function</span> (<span class="params">event, fn</span>) </span>&#123;&#125;</span><br><span class="line"></span><br><span class="line">  <span class="comment">// 定义$once</span></span><br><span class="line">  Vue.prototype.$once = <span class="function"><span class="keyword">function</span> (<span class="params">event, fn</span>) </span>&#123;&#125;</span><br><span class="line"></span><br><span class="line">  <span class="comment">// 定义$off</span></span><br><span class="line">  Vue.prototype.$off = <span class="function"><span class="keyword">function</span> (<span class="params">event, fn</span>) </span>&#123;&#125;</span><br><span class="line"></span><br><span class="line">  <span class="comment">// 定义$emit</span></span><br><span class="line">  Vue.prototype.$emit = <span class="function"><span class="keyword">function</span> (<span class="params">event</span>) </span>&#123;&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h4 id="on-的实现"><a href="#on-的实现" class="headerlink" title="$on 的实现"></a>$on 的实现</h4><ul>
<li><p><strong>参数</strong>：</p>
<ul>
<li><code>&#123;string | Array&lt;string&gt;&#125; event</code> (数组只在 2.2.0+ 中支持)</li>
<li><code>&#123;Function&#125; callback</code></li>
</ul>
</li>
<li><p><strong>用法</strong>：</p>
<p>监听当前实例上的自定义事件。事件可以由 <code>vm.$emit</code> 触发。回调函数会接收所有传入事件触发函数的额外参数。</p>
</li>
</ul>
<p><code>$on</code>方法可以接受一个数组<code>event</code>，当传递一个<code>event</code>数组时，会通过遍历数组的形式递归调用<code>$on</code>方法。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line">Vue.prototype.$on = <span class="function"><span class="keyword">function</span> (<span class="params">event: string | <span class="built_in">Array</span>&lt;string&gt;, fn: <span class="built_in">Function</span></span>): <span class="title">Component</span> </span>&#123;</span><br><span class="line">  <span class="keyword">const</span> vm: Component = <span class="built_in">this</span></span><br><span class="line">  <span class="comment">// 第一个参数是数组，递归处理</span></span><br><span class="line">  <span class="keyword">if</span> (<span class="built_in">Array</span>.isArray(event)) &#123;</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">0</span>, l = event.length; i &lt; l; i++) &#123;</span><br><span class="line">      vm.$on(event[i], fn)</span><br><span class="line">    &#125;</span><br><span class="line">  &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">    <span class="comment">// 将事件添加到 _events 对象下</span></span><br><span class="line">    (vm._events[event] || (vm._events[event] = [])).push(fn)</span><br><span class="line">    <span class="comment">// optimize hook:event cost by using a boolean flag marked at registration</span></span><br><span class="line">    <span class="comment">// instead of a hash lookup</span></span><br><span class="line">    <span class="keyword">if</span> (hookRE.test(event)) &#123;</span><br><span class="line">      vm._hasHookEvent = <span class="literal">true</span></span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">return</span> vm</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h4 id="emit-的实现"><a href="#emit-的实现" class="headerlink" title="$emit 的实现"></a>$emit 的实现</h4><p><strong>参数</strong>：</p>
<ul>
<li><code>&#123;string&#125; eventName</code></li>
<li><code>[...args]</code></li>
</ul>
<p>触发当前实例上的事件。附加参数都会传给监听器回调。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">Vue.prototype.$emit = <span class="function"><span class="keyword">function</span> (<span class="params">event: string</span>): <span class="title">Component</span> </span>&#123;</span><br><span class="line">  <span class="keyword">const</span> vm: Component = <span class="built_in">this</span></span><br><span class="line">  <span class="comment">// ...省略处理边界代码</span></span><br><span class="line">  <span class="keyword">let</span> cbs = vm._events[event]</span><br><span class="line">  <span class="keyword">if</span> (cbs) &#123;</span><br><span class="line">    cbs = cbs.length &gt; <span class="number">1</span> ? toArray(cbs) : cbs</span><br><span class="line">    <span class="keyword">const</span> args = toArray(<span class="built_in">arguments</span>, <span class="number">1</span>)</span><br><span class="line">    <span class="keyword">const</span> info = <span class="string">`event handler for &quot;<span class="subst">$&#123;event&#125;</span>&quot;`</span></span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">0</span>, l = cbs.length; i &lt; l; i++) &#123;</span><br><span class="line">      invokeWithErrorHandling(cbs[i], vm, args, vm, info)</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">return</span> vm</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>代码分析：</p>
<ul>
<li><p>从整体上看，<code>$emit</code>实现方法非常简单，第一步从<code>_events</code>对象中取出对应的<code>cbs</code>，接着一个个遍历<code>cbs</code>数组、调用并传参。</p>
</li>
<li><p><code>invokeWithErrorHandling</code>代码中会使用<code>try/catch</code>把我们函数调用并执行的地方包裹起来，当函数调用出错时，会执行<code>Vue</code>的<code>handleError()</code>方法，这种做法不仅更加友好，而且对错误处理也非常有用。</p>
</li>
</ul>
<h4 id="off-的实现"><a href="#off-的实现" class="headerlink" title="$off 的实现"></a>$off 的实现</h4><ul>
<li><p><strong>参数</strong>：</p>
<ul>
<li><code>&#123;string | Array&lt;string&gt;&#125; event</code> (只在 2.2.2+ 支持数组)</li>
<li><code>&#123;Function&#125; [callback]</code></li>
</ul>
</li>
<li><p><strong>用法</strong>：</p>
<p>移除自定义事件监听器。</p>
<ul>
<li>如果没有提供参数，则移除所有的事件监听器；</li>
<li>如果只提供了事件，则移除该事件所有的监听器；</li>
<li>如果同时提供了事件与回调，则只移除这个回调的监听器。</li>
</ul>
</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 注销事件处理逻辑；_events 对象是存储所有注册对事件</span></span><br><span class="line"><span class="comment"> * 1、如果不传参数，注销所有事件</span></span><br><span class="line"><span class="comment"> * 2、如果第一个参数是数组，则进行递归处理</span></span><br><span class="line"><span class="comment"> * 3、只闯入一个参数，注销该类型事件</span></span><br><span class="line"><span class="comment"> * 4、如果传人两个参数，遍历删除该注册事件</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param <span class="type">&#123;*&#125;</span> </span>event </span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param <span class="type">&#123;*&#125;</span> </span>fn </span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line">Vue.prototype.$off = <span class="function"><span class="keyword">function</span> (<span class="params">event?: string | <span class="built_in">Array</span>&lt;string&gt;, fn?: <span class="built_in">Function</span></span>): <span class="title">Component</span> </span>&#123;</span><br><span class="line">  <span class="keyword">const</span> vm: Component = <span class="built_in">this</span></span><br><span class="line">  <span class="comment">// all 不传参数，清空所有到事件</span></span><br><span class="line">  <span class="keyword">if</span> (!<span class="built_in">arguments</span>.length) &#123;</span><br><span class="line">    vm._events = <span class="built_in">Object</span>.create(<span class="literal">null</span>)</span><br><span class="line">    <span class="keyword">return</span> vm</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="comment">// array of events</span></span><br><span class="line">  <span class="keyword">if</span> (<span class="built_in">Array</span>.isArray(event)) &#123;</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">0</span>, l = event.length; i &lt; l; i++) &#123;</span><br><span class="line">      vm.$off(event[i], fn)</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> vm</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="comment">// specific event</span></span><br><span class="line">  <span class="keyword">const</span> cbs = vm._events[event]</span><br><span class="line">  <span class="keyword">if</span> (!cbs) &#123;</span><br><span class="line">    <span class="keyword">return</span> vm</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">if</span> (!fn) &#123;</span><br><span class="line">    vm._events[event] = <span class="literal">null</span></span><br><span class="line">    <span class="keyword">return</span> vm</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="comment">// specific handler</span></span><br><span class="line">  <span class="keyword">let</span> cb</span><br><span class="line">  <span class="keyword">let</span> i = cbs.length</span><br><span class="line">  <span class="keyword">while</span> (i--) &#123;</span><br><span class="line">    cb = cbs[i]</span><br><span class="line">    <span class="keyword">if</span> (cb === fn || cb.fn === fn) &#123;</span><br><span class="line">      cbs.splice(i, <span class="number">1</span>)</span><br><span class="line">      <span class="keyword">break</span></span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">return</span> vm</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<p><code>$off</code>方法的实现，相对来说比较复杂一点，因为它需要根据不同的传参做不同的事情：</p>
<ul>
<li>当没有提供任何参数时，移除全部事件监听。</li>
<li>当只提供<code>event</code>参数时，只移除此<code>event</code>对应的监听器。</li>
<li>同时提供<code>event</code>参数和<code>fn</code>回调，则只移除此<code>event</code>对应的<code>fn</code>这个监听器。</li>
</ul>
<h4 id="once-的实现"><a href="#once-的实现" class="headerlink" title="$once 的实现"></a>$once 的实现</h4><ul>
<li><p><strong>参数</strong>：</p>
<ul>
<li><code>&#123;string&#125; event</code></li>
<li><code>&#123;Function&#125; callback</code></li>
</ul>
</li>
<li><p><strong>用法</strong>：</p>
<p>监听一个自定义事件，但是只触发一次。一旦触发之后，监听器就会被移除。</p>
</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 只监听一次事件处理流程</span></span><br><span class="line"><span class="comment"> * 1、$on 注册事件处理流程</span></span><br><span class="line"><span class="comment"> * 2、监听过后，取消监听，执行函数</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param <span class="type">&#123;*&#125;</span> </span>event </span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param <span class="type">&#123;*&#125;</span> </span>fn </span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line">Vue.prototype.$once = <span class="function"><span class="keyword">function</span> (<span class="params">event: string, fn: <span class="built_in">Function</span></span>): <span class="title">Component</span> </span>&#123;</span><br><span class="line">  <span class="keyword">const</span> vm: Component = <span class="built_in">this</span></span><br><span class="line">  <span class="function"><span class="keyword">function</span> <span class="title">on</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">    vm.$off(event, on)</span><br><span class="line">    fn.apply(vm, <span class="built_in">arguments</span>)</span><br><span class="line">  &#125;</span><br><span class="line">  on.fn = fn</span><br><span class="line">  vm.$on(event, on)</span><br><span class="line">  <span class="keyword">return</span> vm</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p><strong>注意</strong>：在源码中<code>$once</code>的实现是在回调函数中使用<code>fn</code>绑定了原回调函数的引用，在上面已经提到过的<code>$off</code>方法中也同样进行了<code>cb.fn === fn</code>的判断。</p>
<h3 id="lifecycleMixin-流程"><a href="#lifecycleMixin-流程" class="headerlink" title="lifecycleMixin 流程"></a>lifecycleMixin 流程</h3><p><code>lifecycleMixin</code>主要是定义实例方法和生命周期，例如：<code>$forceUpdate()</code>、<code>$destroy</code>，另外它还定义一个<code>_update</code>的私有方法，其中当调用<code>$forceUpdate()</code>方法强制组件重新渲染时会调用这个方法，<code>lifecycleMixin</code>精简代码如下：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">export</span> <span class="function"><span class="keyword">function</span> <span class="title">lifecycleMixin</span> (<span class="params">Vue</span>) </span>&#123;</span><br><span class="line">  <span class="comment">// 私有方法</span></span><br><span class="line">  Vue.prototype._update = <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;&#125;</span><br><span class="line"></span><br><span class="line">  <span class="comment">// 实例方法</span></span><br><span class="line">  Vue.prototype.$forceUpdate = <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (<span class="built_in">this</span>._watcher) &#123;</span><br><span class="line">      <span class="built_in">this</span>._watcher.update()</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">  Vue.prototype.$destroy = <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>代码分析：</p>
<ul>
<li><code>_update()</code>会在组件渲染的时候调用，其具体的实现我们会在组件章节详细介绍。</li>
<li><code>$forceUpdate()</code>为一个强制<code>Vue</code>实例重新渲染的方法，它的内部调用了<code>_update</code>，也就是强制组件重新编译渲染。</li>
<li><code>$destroy()</code>为组件销毁方法，在其具体的实现中，会处理父子组件的关系，事件监听，触发生命周期等操作。</li>
</ul>
<h3 id="renderMixin-流程"><a href="#renderMixin-流程" class="headerlink" title="renderMixin 流程"></a>renderMixin 流程</h3><p>原型上添加运行时辅助工具方法， <code>$nextTick</code>, <code>_render</code> 方法</p>
<ul>
<li><code>$nextTick</code> 异步队列更新，它和 <code>Promise</code> 实现有关</li>
<li><code>_render</code> 内部方法，调用编译生成的 <code>render</code> 函数，将 <code>template</code> 模版生成 <code>vnode tree</code></li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">export</span> <span class="function"><span class="keyword">function</span> <span class="title">renderMixin</span> (<span class="params">Vue</span>) </span>&#123;</span><br><span class="line">  <span class="comment">// 挂载各种私有方法，例如this._c，this._v等</span></span><br><span class="line">  installRenderHelpers(Vue.prototype)</span><br><span class="line">  Vue.prototype._render = <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;&#125;</span><br><span class="line"></span><br><span class="line">  <span class="comment">// 实例方法</span></span><br><span class="line">  Vue.prototype.$nextTick = <span class="function"><span class="keyword">function</span> (<span class="params">fn</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> nextTick(fn, <span class="built_in">this</span>)</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>代码分析：</p>
<ul>
<li><code>installRenderHelpers</code>：它会在<code>Vue.prototype</code>上挂载各种私有方法，例如<code>this._n = toNumber</code>、<code>this._s = toString</code>、<code>this._v = createTextVNode</code>和<code>this._e = createEmptyVNode</code>。</li>
<li><code>_render()</code>：<code>_render()</code>方法会把模板编译成<code>VNode</code>，我们会在其后的编译章节详细介绍。</li>
<li><code>nextTick</code>：就像我们之前介绍过的，<code>nextTick</code>会在<code>Vue</code>构造函数上挂载一个全局的<code>nextTick()</code>方法，而此处为实例方法，本质上引用的是同一个<code>nextTick</code>。</li>
</ul>
<h2 id="Vue-实例化和挂载执行流程图"><a href="#Vue-实例化和挂载执行流程图" class="headerlink" title="Vue 实例化和挂载执行流程图"></a>Vue 实例化和挂载执行流程图</h2><p><a data-fancybox target="_blank" rel="noopener" href="http://assets.processon.com/chart_image/6040fb5107912951ff326adb.png"><img src= "" data-lazy-src="http://assets.processon.com/chart_image/6040fb5107912951ff326adb.png" alt="挂载流程图"></a></p>
<h2 id="Vue执行流程思维导图"><a href="#Vue执行流程思维导图" class="headerlink" title="Vue执行流程思维导图"></a>Vue执行流程思维导图</h2><p><a target="_blank" rel="noopener" href="https://www.processon.com/view/link/605e9c67f346fb6d9eeb6c4a">Vue执行流程思维导图</a></p>
<h2 id="Runtime-Only-VS-Runtime-Compiler"><a href="#Runtime-Only-VS-Runtime-Compiler" class="headerlink" title="Runtime Only VS Runtime + Compiler"></a>Runtime Only VS Runtime + Compiler</h2><p>当执行 <code>import Vue from &#39;vue&#39;</code> 的时候，从源码入口开始初始化。 <code>vue</code> 基于源码构建有两个版本，一个是 <code>runtime only</code> (只包含运行时的版本)，另一个是 <code>runtime + compiler</code> (同时包含编译器和运行时的版本)。两个版本的区别仅在于后者包含了一个编译器，内置的编译器实现了将 <code>template</code> 模板转换编译为可执行 <code>javascript</code> 脚本的功能。</p>
<h3 id="Runtime-Compiler"><a href="#Runtime-Compiler" class="headerlink" title="Runtime + Compiler"></a>Runtime + Compiler</h3><p>一个完整的 <code>Vue</code> 版本是包含编译器的，我们可以使用 <code>template</code> 进行模板编写。编译器会自动将模板字符串编译成渲染函数的代码, 源码中就是 <code>render</code> 函数。如果你需要在客户端编译模板 (比如传入一个字符串给 <code>template</code> 选项，或挂载到一个元素上并以其 <code>DOM</code> 内部的 <code>HTML</code> 作为模板)，就需要一个包含编译器的版本。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 需要编译器的版本</span></span><br><span class="line"><span class="keyword">new</span> Vue(&#123;</span><br><span class="line">  template: <span class="string">&#x27;&lt;div&gt;&#123;&#123; hi &#125;&#125;&lt;/div&gt;&#x27;</span></span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>

<h3 id="Runtime-Only"><a href="#Runtime-Only" class="headerlink" title="Runtime Only"></a>Runtime Only</h3><p>只包含运行时的代码拥有创建 <code>Vue</code> 实例、渲染并处理 <code>Virtual DOM</code> 等功能，基本上就是除去编译器外的完整代码。<code>Runtime Only</code> 的适用场景：我们在选项中通过手写 <code>render</code> 函数去定义渲染过程，这个时候并不需要包含编译器的版本便可完整执行。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 不需要编译器</span></span><br><span class="line"><span class="keyword">new</span> Vue(&#123;</span><br><span class="line">  render (h) &#123;</span><br><span class="line">    <span class="keyword">return</span> h(<span class="string">&#x27;div&#x27;</span>, <span class="built_in">this</span>.hi)</span><br><span class="line">  &#125;</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>

<h2 id="Vue-源码构建入口"><a href="#Vue-源码构建入口" class="headerlink" title="Vue 源码构建入口"></a>Vue 源码构建入口</h2><p>当执行 <code>npm run dev</code>,  <code>vue</code> 构建的版本是 <code>Runtime + Compiler</code>, 它的入口文件是 <code>src/platforms/web/entry-runtime-with-compiler.js</code>：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> Vue <span class="keyword">from</span> <span class="string">&#x27;./runtime/index&#x27;</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 缓存 $mount 方法</span></span><br><span class="line"><span class="keyword">const</span> mount = Vue.prototype.$mount</span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 重写 $mount 方法，使用 compileToFunctions 编译 template 或 el 为 render 函数</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param <span class="type">&#123;*&#125;</span> <span class="variable">el</span></span></span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param <span class="type">&#123;*&#125;</span> <span class="variable">hydrating</span></span></span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line">Vue.prototype.$mount = <span class="function"><span class="keyword">function</span> (<span class="params"></span></span></span><br><span class="line"><span class="function"><span class="params">  el?: string | Element, <span class="comment">// 接收字符串或 DOM 元素</span></span></span></span><br><span class="line"><span class="function"><span class="params">  hydrating?: boolean <span class="comment">// 是否是服务端渲染</span></span></span></span><br><span class="line"><span class="function"><span class="params"></span>): <span class="title">Component</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">  <span class="comment">//...</span></span><br><span class="line">  <span class="comment">// 最后重新调用缓存的 $mount方法</span></span><br><span class="line">  <span class="keyword">return</span> mount.call(<span class="built_in">this</span>, el, hydrating)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> Vue</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h2 id="Vue-的入口"><a href="#Vue-的入口" class="headerlink" title="Vue 的入口"></a>Vue 的入口</h2><p>在上方这个构建入口 JS 的我们可以找到 Vue 的来源：<code>import Vue from &#39;./runtime/index&#39;</code>，先来看一下这块儿的实现，它定义在 <code>src/platforms/web/runtime/index.js</code> 中：new Vue 做了什么</p>
<p>从上面源码分析我们知道，<code>new Vue</code> 会执行 <code>_init</code> 方法</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">Vue</span> (<span class="params">options</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">if</span> (process.env.NODE_ENV !== <span class="string">&#x27;production&#x27;</span> &amp;&amp;</span><br><span class="line">    !(<span class="built_in">this</span> <span class="keyword">instanceof</span> Vue)</span><br><span class="line">  ) &#123;</span><br><span class="line">    warn(<span class="string">&#x27;Vue is a constructor and should be called with the `new` keyword&#x27;</span>)</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="built_in">this</span>._init(options)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<p><code>_init</code> 方法会进行选型合并配置，数据代理，初始化组件将当前 vm 实例添加到父类上，建立组成层级关系。初始化事件中心将父组件监听事件注册到子组件上，初始化渲染，初始化 <code>props</code>、<code>methods</code>、<code>data</code>、<code>computed</code>、<code>watcher</code>，执行生命周期钩子函数, 调用 <code>$mount</code> 手动挂载 <code>DOM</code>。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line">Vue.prototype._init = <span class="function"><span class="keyword">function</span> (<span class="params">options</span>) </span>&#123;</span><br><span class="line">  ···</span><br><span class="line">  <span class="comment">// 选项合并</span></span><br><span class="line">  vm.$options = mergeOptions(</span><br><span class="line">    resolveConstructorOptions(vm.constructor),</span><br><span class="line">    options || &#123;&#125;,</span><br><span class="line">    vm</span><br><span class="line">  );</span><br><span class="line">  <span class="comment">// 数据代理</span></span><br><span class="line">  initProxy(vm);</span><br><span class="line">  vm._self = vm;</span><br><span class="line">  <span class="comment">// 创建组件关联</span></span><br><span class="line">  initLifecycle(vm);</span><br><span class="line">  <span class="comment">// 初始化事件处理</span></span><br><span class="line">  initEvents(vm);</span><br><span class="line">  <span class="comment">// 定义渲染函数</span></span><br><span class="line">  initRender(vm);</span><br><span class="line">  <span class="comment">// 构建响应式系统</span></span><br><span class="line">  initState(vm);</span><br><span class="line">  <span class="comment">// 等等</span></span><br><span class="line">  ···</span><br><span class="line">  <span class="keyword">if</span> (vm.$options.el) &#123;</span><br><span class="line">    vm.$mount(vm.$options.el);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><code>_init</code> 方法进行一系列初始化过程后，执行挂载 <code>$mount</code></p>
<h3 id="挂载代码分析"><a href="#挂载代码分析" class="headerlink" title="挂载代码分析"></a>挂载代码分析</h3><p>内部真正实现挂载的方法</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 内部真正实现挂载的方法</span></span><br><span class="line">Vue.prototype.$mount = <span class="function"><span class="keyword">function</span> (<span class="params">el, hydrating</span>) </span>&#123;</span><br><span class="line">  el = el &amp;&amp; inBrowser ? query(el) : <span class="literal">undefined</span>;</span><br><span class="line">  <span class="comment">// 调用mountComponent方法挂载</span></span><br><span class="line">  <span class="keyword">return</span> mountComponent(<span class="built_in">this</span>, el, hydrating)</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>



<p>如果是 <code>runtime + compiler</code> 版本的 <code>vue</code>，会走下面的逻辑，在 <code>$mount</code> 方法外再套一层，目的是添加编译器，编译器主要做三件事情：</p>
<ul>
<li>parse 解析器：调用 <code>parse </code> 方法，执行 <code>parseHTML</code> 通过正则匹配将 <code>template</code> 解析为 <code>AST</code> 抽象语法树</li>
<li>optimize 优化器：调用<code>optimize</code> 方法，为元素打上静态节点和根静态节点标识，目的是 <code>diff</code> 对比更新减少编译过程优化性能</li>
<li>codegen 代码生成器：将 <code>AST</code> 转化为 可执行代码 <code>render</code> 函数</li>
</ul>
<p>所以， <code>template</code> 模版经过编译后得到 <code>render</code> 函数赋值给 <code>options</code> </p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 缓存了原型上的 $mount 方法</span></span><br><span class="line"><span class="keyword">var</span> mount = Vue.prototype.$mount;</span><br><span class="line"><span class="comment">// 重新定义$mount,为包含编译器和不包含编译器的版本提供不同封装，最终调用的是缓存原型上的$mount方法</span></span><br><span class="line">Vue.prototype.$mount = <span class="function"><span class="keyword">function</span> (<span class="params">el, hydrating</span>) </span>&#123;</span><br><span class="line">  <span class="comment">// 获取挂载元素</span></span><br><span class="line">  el = el &amp;&amp; query(el);</span><br><span class="line">  <span class="comment">// 挂载元素不能为跟节点</span></span><br><span class="line">  <span class="keyword">if</span> (el === <span class="built_in">document</span>.body || el === <span class="built_in">document</span>.documentElement) &#123;</span><br><span class="line">    warn(</span><br><span class="line">      <span class="string">&quot;Do not mount Vue to &lt;html&gt; or &lt;body&gt; - mount to normal elements instead.&quot;</span></span><br><span class="line">    );</span><br><span class="line">    <span class="keyword">return</span> <span class="built_in">this</span></span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">var</span> options = <span class="built_in">this</span>.$options;</span><br><span class="line">  <span class="comment">// 需要编译 or 不需要编译</span></span><br><span class="line">  <span class="comment">// render选项不存在，代表是template模板的形式，此时需要进行模板的编译过程</span></span><br><span class="line">  <span class="keyword">if</span> (!options.render) &#123;</span><br><span class="line">    ···</span><br><span class="line">    <span class="comment">// 使用内部编译器编译模板</span></span><br><span class="line">  &#125;</span><br><span class="line">  <span class="comment">// 无论是template模板还是手写render函数最终调用缓存的$mount方法</span></span><br><span class="line">  <span class="keyword">return</span> mount.call(<span class="built_in">this</span>, el, hydrating)</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p><code>mountComponent</code> 挂载组件，会实例化 <code>Watch</code>，在回调函数中执行 <code>updateComponent</code> 方法，<code>updateComponent</code> 主要做两件事</p>
<ul>
<li>调用 <code>_render</code> 方法，执行 <code>render</code> 函数，得到 <code>vnode</code> </li>
<li>调用 <code>_update</code> 方法，执行 <code>patch</code> 函数，将 <code>vnode</code> 生成真实的 <code>DOM</code> 节点</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// mountComponent方法思路</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">mountComponent</span>(<span class="params">vm, el, hydrating</span>) </span>&#123;</span><br><span class="line">  <span class="comment">// 定义updateComponent方法，在watch回调时调用。</span></span><br><span class="line">  updateComponent = <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="comment">// render函数渲染成虚拟DOM， 虚拟DOM渲染成真实的DOM</span></span><br><span class="line">    vm._update(vm._render(), hydrating);</span><br><span class="line">  &#125;;</span><br><span class="line">  <span class="comment">// 实例化渲染watcher</span></span><br><span class="line">  <span class="keyword">new</span> Watcher(vm, updateComponent, noop, &#123;&#125;)</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>



<h2 id="Vue-调试"><a href="#Vue-调试" class="headerlink" title="Vue 调试"></a>Vue 调试</h2><p><code>vue</code> 源码整个构建流程说完了，接下来就是启动项目调试，过程很简单。</p>
<p><code>vue</code> 项目有个 <code>example</code> 目录，它是引用 <code>dist</code> 目录下 <code>vue</code> 文件的一些 <code>demo</code>，也可以创建一个包含 <code>html</code> 和 <code>js</code> 文件的目录，如果想直接在服务上打开 <code>html</code> 文件，可以安装 <code>VSC</code> 编译器的 <code>Live Server</code> 插件，无需安装服务软件就可以打开一个静态页面，执行 <code>npm</code> 命令痛快的打断点调试了</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">git <span class="built_in">clone</span>  https://github.com/vuejs/vue.git</span><br><span class="line"></span><br><span class="line">安装 VSC 插件 live Sever</span><br><span class="line"></span><br><span class="line">npm install</span><br><span class="line"></span><br><span class="line">npm run dev</span><br><span class="line"></span><br><span class="line">断点调试</span><br></pre></td></tr></table></figure>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="mailto:undefined">志非</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://fif.gitee.io/blog/2021/04/17/vue/vue-code-4.debugger/">https://fif.gitee.io/blog/2021/04/17/vue/vue-code-4.debugger/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://fif.gitee.io/blog" target="_blank">Jeffery Blog</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/blog/tags/vue/">vue</a><a class="post-meta__tags" href="/blog/tags/vue-%E6%BA%90%E7%A0%81/">vue 源码</a></div><div class="post_share"><div class="social-share" data-image="https://gitee.com/FIF/pic-beg/raw/master/images/vue/1_b2Ig4HR2UOQEV5I2QnQrrw.png" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/social-share.js/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/social-share.js/dist/js/social-share.min.js" defer></script></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/blog/2021/04/23/vue/vue-code-5.mergeOptions/"><img class="prev-cover" src= "" data-lazy-src="https://gitee.com/FIF/pic-beg/raw/master/images/vue/vue-highcharts_1200.webp" onerror="onerror=null;src='/blog/img/404.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">（Vue源码三）Vue 丰富的选项合并策略</div></div></a></div><div class="next-post pull-right"><a href="/blog/2021/04/12/vue/vue-code-3.build/"><img class="next-cover" src= "" data-lazy-src="https://gitee.com/FIF/pic-beg/raw/master/images/vue/Vue.js-i18n-768x512.jpg" onerror="onerror=null;src='/blog/img/404.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">（Vue源码一）Vue 源码设计和构建流程</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span> 相关推荐</span></div><div class="relatedPosts-list"><div><a href="/blog/2021/04/12/vue/vue-code-3.build/" title="（Vue源码一）Vue 源码设计和构建流程"><img class="cover" src= "" data-lazy-src="https://gitee.com/FIF/pic-beg/raw/master/images/vue/Vue.js-i18n-768x512.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-04-12</div><div class="title">（Vue源码一）Vue 源码设计和构建流程</div></div></a></div><div><a href="/blog/2021/04/23/vue/vue-code-5.mergeOptions/" title="（Vue源码三）Vue 丰富的选项合并策略"><img class="cover" src= "" data-lazy-src="https://gitee.com/FIF/pic-beg/raw/master/images/vue/vue-highcharts_1200.webp" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-04-23</div><div class="title">（Vue源码三）Vue 丰富的选项合并策略</div></div></a></div><div><a href="/blog/2021/04/30/vue/vue-code-7-compiler/" title="（Vue源码五）Vue 编译原理"><img class="cover" src= "" data-lazy-src="https://gitee.com/FIF/pic-beg/raw/master/images/vue/vuetemplate.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-04-30</div><div class="title">（Vue源码五）Vue 编译原理</div></div></a></div><div><a href="/blog/2021/05/04/vue/vue-code-8.component/" title="（Vue源码六）Vue 组件原理分析"><img class="cover" src= "" data-lazy-src="https://gitee.com/FIF/pic-beg/raw/master/images/vue/components.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-05-04</div><div class="title">（Vue源码六）Vue 组件原理分析</div></div></a></div><div><a href="/blog/2021/04/27/vue/vue-code-6.reactive/" title="（Vue源码四）数据响应式原理"><img class="cover" src= "" data-lazy-src="https://gitee.com/FIF/pic-beg/raw/master/images/vue/mvvm.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-04-27</div><div class="title">（Vue源码四）数据响应式原理</div></div></a></div><div><a href="/blog/2021/05/14/vue/vue-code-9.event/" title="（Vue源码七）Vue 事件"><img class="cover" src= "" data-lazy-src="https://gitee.com/FIF/pic-beg/raw/master/images/vue/components.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-05-14</div><div class="title">（Vue源码七）Vue 事件</div></div></a></div></div></div><hr/><div id="post-comment"><div class="comment-head"><div class="comment-headline"><i class="fas fa-comments fa-fw"></i><span> 评论</span></div></div><div class="comment-wrap"><div><div class="vcomment" id="vcomment"></div></div></div></div></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="card-info-avatar is-center"><img class="avatar-img" src= "" data-lazy-src="/blog/img/home/avatar.jpeg" onerror="this.onerror=null;this.src='/blog/img/friend_404.gif'" alt="avatar"/><div class="author-info__name">志非</div><div class="author-info__description">自己变得更好，生活才会更美好</div></div><div class="card-info-data"><div class="card-info-data-item is-center"><a href="/blog/archives/"><div class="headline">文章</div><div class="length-num">12</div></a></div><div class="card-info-data-item is-center"><a href="/blog/tags/"><div class="headline">标签</div><div class="length-num">6</div></a></div><div class="card-info-data-item is-center"><a href="/blog/categories/"><div class="headline">分类</div><div class="length-num">7</div></a></div></div><a class="button--animated" id="card-info-btn" target="_blank" rel="noopener" href="https://github.com/JefferyXZF"><i class="fab fa-github"></i><span>Follow Me</span></a><div class="card-info-social-icons is-center"><a class="social-icon" href="https://github.com/JefferyXZF" target="_blank" title="Github"><i class="fab fa-github"></i></a><a class="social-icon" href="https://www.yuque.com/jeffery-kkrpn/uz24n9" target="_blank" title="语雀"><i class="fa fa-folder-open"></i></a><a class="social-icon" href="https://mail.qq.com/" target="_blank" title="Email"><i class="fas fa-envelope"></i></a></div></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn card-announcement-animation"></i><span>公告</span></div><div class="announcement_content">越努力越幸运</div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#Vue%E5%87%BD%E6%95%B0%E6%8C%82%E8%BD%BDAPI"><span class="toc-number">1.</span> <span class="toc-text">Vue函数挂载API</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#initGlobalAPI%E6%8C%82%E8%BD%BD%E5%85%A8%E5%B1%80%E6%96%B9%E6%B3%95"><span class="toc-number">2.</span> <span class="toc-text">initGlobalAPI挂载全局方法</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%8C%82%E8%BD%BD%E5%8E%9F%E5%9E%8B%E6%96%B9%E6%B3%95"><span class="toc-number">3.</span> <span class="toc-text">挂载原型方法</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#initMixin-%E6%B5%81%E7%A8%8B"><span class="toc-number">3.1.</span> <span class="toc-text">initMixin 流程</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#stateMixin-%E6%B5%81%E7%A8%8B"><span class="toc-number">3.2.</span> <span class="toc-text">stateMixin 流程</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#eventsMixin-%E6%B5%81%E7%A8%8B"><span class="toc-number">3.3.</span> <span class="toc-text">eventsMixin 流程</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#on-%E7%9A%84%E5%AE%9E%E7%8E%B0"><span class="toc-number">3.3.1.</span> <span class="toc-text">$on 的实现</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#emit-%E7%9A%84%E5%AE%9E%E7%8E%B0"><span class="toc-number">3.3.2.</span> <span class="toc-text">$emit 的实现</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#off-%E7%9A%84%E5%AE%9E%E7%8E%B0"><span class="toc-number">3.3.3.</span> <span class="toc-text">$off 的实现</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#once-%E7%9A%84%E5%AE%9E%E7%8E%B0"><span class="toc-number">3.3.4.</span> <span class="toc-text">$once 的实现</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#lifecycleMixin-%E6%B5%81%E7%A8%8B"><span class="toc-number">3.4.</span> <span class="toc-text">lifecycleMixin 流程</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#renderMixin-%E6%B5%81%E7%A8%8B"><span class="toc-number">3.5.</span> <span class="toc-text">renderMixin 流程</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Vue-%E5%AE%9E%E4%BE%8B%E5%8C%96%E5%92%8C%E6%8C%82%E8%BD%BD%E6%89%A7%E8%A1%8C%E6%B5%81%E7%A8%8B%E5%9B%BE"><span class="toc-number">4.</span> <span class="toc-text">Vue 实例化和挂载执行流程图</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Vue%E6%89%A7%E8%A1%8C%E6%B5%81%E7%A8%8B%E6%80%9D%E7%BB%B4%E5%AF%BC%E5%9B%BE"><span class="toc-number">5.</span> <span class="toc-text">Vue执行流程思维导图</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Runtime-Only-VS-Runtime-Compiler"><span class="toc-number">6.</span> <span class="toc-text">Runtime Only VS Runtime + Compiler</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#Runtime-Compiler"><span class="toc-number">6.1.</span> <span class="toc-text">Runtime + Compiler</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Runtime-Only"><span class="toc-number">6.2.</span> <span class="toc-text">Runtime Only</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Vue-%E6%BA%90%E7%A0%81%E6%9E%84%E5%BB%BA%E5%85%A5%E5%8F%A3"><span class="toc-number">7.</span> <span class="toc-text">Vue 源码构建入口</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Vue-%E7%9A%84%E5%85%A5%E5%8F%A3"><span class="toc-number">8.</span> <span class="toc-text">Vue 的入口</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%8C%82%E8%BD%BD%E4%BB%A3%E7%A0%81%E5%88%86%E6%9E%90"><span class="toc-number">8.1.</span> <span class="toc-text">挂载代码分析</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Vue-%E8%B0%83%E8%AF%95"><span class="toc-number">9.</span> <span class="toc-text">Vue 调试</span></a></li></ol></div></div><script defer="defer" data-pjax="data-pjax" src="/blog/js/card_clock.js"></script><div class="card-widget card-clock"><div id="clock"><img v-if="clockshow == &quot;false&quot;" alt="" src= "" data-lazy-src="/blog/img/weather/loading.gif" height="120px" width="100%"/><table class="clock" v-if="clockshow"><tbody><tr><td class="clockdate">{{date}}</td><td class="weatherimg"><img id="weatherimg" :src="weatherimg" alt=""/></td><td class="temperature">{{temperature}}</td><td class="humidityimg"><img id="humidityimg" :src="humidityimg" alt=""/></td><td class="humidity">{{humidity}}</td></tr><tr class="time"><td colspan="5">{{time}}</td></tr><tr><td class="usaqi" colspan="1"><span>{{ip}}</span></td><td class="city" colspan="2">{{city}}</td><td class="daylight" colspan="2">{{daylight}}</td></tr></tbody></table></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item"><a class="thumbnail" href="/blog/2021/05/24/tools/hexo/advanced/" title="Hexo 博客页面性能优化"><img src= "" data-lazy-src="https://gitee.com/FIF/pic-beg/raw/master/images/vue/Hexo-logo.png" onerror="this.onerror=null;this.src='/blog/img/404.jpg'" alt="Hexo 博客页面性能优化"/></a><div class="content"><a class="title" href="/blog/2021/05/24/tools/hexo/advanced/" title="Hexo 博客页面性能优化">Hexo 博客页面性能优化</a><time datetime="2021-05-23T16:00:00.000Z" title="发表于 2021-05-24 00:00:00">2021-05-24</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/blog/2021/05/14/vue/vue-code-9.event/" title="（Vue源码七）Vue 事件"><img src= "" data-lazy-src="https://gitee.com/FIF/pic-beg/raw/master/images/vue/components.png" onerror="this.onerror=null;this.src='/blog/img/404.jpg'" alt="（Vue源码七）Vue 事件"/></a><div class="content"><a class="title" href="/blog/2021/05/14/vue/vue-code-9.event/" title="（Vue源码七）Vue 事件">（Vue源码七）Vue 事件</a><time datetime="2021-05-13T16:00:00.000Z" title="发表于 2021-05-14 00:00:00">2021-05-14</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/blog/2021/05/04/vue/vue-code-8.component/" title="（Vue源码六）Vue 组件原理分析"><img src= "" data-lazy-src="https://gitee.com/FIF/pic-beg/raw/master/images/vue/components.png" onerror="this.onerror=null;this.src='/blog/img/404.jpg'" alt="（Vue源码六）Vue 组件原理分析"/></a><div class="content"><a class="title" href="/blog/2021/05/04/vue/vue-code-8.component/" title="（Vue源码六）Vue 组件原理分析">（Vue源码六）Vue 组件原理分析</a><time datetime="2021-05-03T16:00:00.000Z" title="发表于 2021-05-04 00:00:00">2021-05-04</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/blog/2021/04/30/vue/vue-code-7-compiler/" title="（Vue源码五）Vue 编译原理"><img src= "" data-lazy-src="https://gitee.com/FIF/pic-beg/raw/master/images/vue/vuetemplate.jpg" onerror="this.onerror=null;this.src='/blog/img/404.jpg'" alt="（Vue源码五）Vue 编译原理"/></a><div class="content"><a class="title" href="/blog/2021/04/30/vue/vue-code-7-compiler/" title="（Vue源码五）Vue 编译原理">（Vue源码五）Vue 编译原理</a><time datetime="2021-04-29T16:00:00.000Z" title="发表于 2021-04-30 00:00:00">2021-04-30</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/blog/2021/04/27/vue/vue-code-6.reactive/" title="（Vue源码四）数据响应式原理"><img src= "" data-lazy-src="https://gitee.com/FIF/pic-beg/raw/master/images/vue/mvvm.png" onerror="this.onerror=null;this.src='/blog/img/404.jpg'" alt="（Vue源码四）数据响应式原理"/></a><div class="content"><a class="title" href="/blog/2021/04/27/vue/vue-code-6.reactive/" title="（Vue源码四）数据响应式原理">（Vue源码四）数据响应式原理</a><time datetime="2021-04-26T16:00:00.000Z" title="发表于 2021-04-27 00:00:00">2021-04-27</time></div></div></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2021 By 志非</div><div class="footer_custom_text">Hi, welcome to my <a href="/">blog</a>!</div><div id="workboard"></div><script async="async" src="/blog/js/runtime.js"></script></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="translateLink" type="button" title="简繁转换">繁</button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="chat_btn" type="button" title="rightside.chat_btn"><i class="fas fa-sms"></i></button><a id="to_comment" href="#post-comment" title="直达评论"><i class="fas fa-comments"></i></a><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button></div></div><div id="algolia-search"><div class="search-dialog"><div class="search-dialog__title" id="algolia-search-title">Algolia</div><div id="algolia-input-panel"><div id="algolia-search-input"></div></div><hr/><div id="algolia-search-results"><div id="algolia-hits"></div><div id="algolia-pagination"></div><div id="algolia-stats"></div></div><span class="search-close-button"><i class="fas fa-times"></i></span></div><div id="search-mask"></div></div><div><script src="https://cdn.jsdelivr.net/npm/vue"></script><script src="/blog/js/utils.js"></script><script src="/blog/js/main.js"></script><script src="/blog/js/tw_cn.js"></script><script src="https://cdn.jsdelivr.net/npm/medium-zoom/dist/medium-zoom.min.js"></script><script src="https://cdn.jsdelivr.net/npm/instant.page/instantpage.min.js" type="module"></script><script src="https://cdn.jsdelivr.net/npm/vanilla-lazyload/dist/lazyload.iife.min.js"></script><script src="https://cdn.jsdelivr.net/npm/node-snackbar/dist/snackbar.min.js"></script><script src="/blog/js/search/algolia.js"></script><script>var preloader = {
  endLoading: () => {
    document.body.style.overflow = 'auto';
    document.getElementById('loading-box').classList.add("loaded")
  },
  initLoading: () => {
    document.body.style.overflow = '';
    document.getElementById('loading-box').classList.remove("loaded")

  }
}
window.addEventListener('load',preloader.endLoading())</script><div class="js-pjax"><script>if (document.getElementsByClassName('mermaid').length) {
  if (window.mermaidJsLoad) mermaid.init()
  else {
    getScript('https://cdn.jsdelivr.net/npm/mermaid/dist/mermaid.min.js').then(() => {
      window.mermaidJsLoad = true
      mermaid.initialize({
        theme: 'default',
      })
      false && mermaid.init()
    })
  }
}</script><script>function loadValine () {
  function initValine () {
    const valine = new Valine(Object.assign({
      el: '#vcomment',
      appId: 'JC72d1A7XBwC26rGCKMVn5CS-MdYXbMMI',
      appKey: 'xI6bG7FseICz8ShKdmWVe7N1',
      placeholder: 'Please leave your footprints',
      avatar: 'https://gitee.com/FIF/pic-beg/raw/master/images/vue/1619248532079-avatar_coment.webp',
      meta: 'nick,mail,link'.split(','),
      pageSize: '10',
      lang: 'zh-CN',
      recordIP: false,
      serverURLs: '',
      emojiCDN: '',
      emojiMaps: "",
      enableQQ: true,
      path: window.location.pathname,
      requiredFields: ["nick,mail"],
      visitor: false,
      avatar_cdn: 'https://www.gravatar.com/avatar/'
    }, null))
  }

  if (typeof Valine === 'function') initValine() 
  else getScript('https://cdn.jsdelivr.net/npm/valine/dist/Valine.min.js').then(initValine)
}

if ('Valine' === 'Valine' || !true) {
  if (true) btf.loadComment(document.getElementById('vcomment'),loadValine)
  else setTimeout(loadValine, 0)
} else {
  function loadOtherComment () {
    loadValine()
  }
}</script></div><div class="aplayer no-destroy" data-id="000PeZCQ1i4XVs" data-server="tencent" data-type="artist" data-fixed="true" data-mini="true" data-listFolded="false" data-order="random" data-preload="none" data-autoplay="false" pjax="true" muted></div><script defer="defer" id="ribbon" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/dist/canvas-ribbon.min.js" size="150" alpha="0.6" zIndex="-1" mobile="false" data-click="true"></script><script id="canvas_nest" defer="defer" color="0,0,255" opacity="0.7" zIndex="-1" count="99" mobile="false" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/dist/canvas-nest.min.js"></script><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/dist/activate-power-mode.min.js"></script><script>POWERMODE.colorful = true;
POWERMODE.shake = true;
POWERMODE.mobile = false;
document.body.addEventListener('input', POWERMODE);
</script><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/aplayer/dist/APlayer.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/aplayer/dist/APlayer.min.js"></script><script src="https://cdn.jsdelivr.net/gh/metowolf/MetingJS@1.2/dist/Meting.min.js"></script><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div></body></html>